package com.hyjoy.web.servlet;

import com.hyjoy.entity.Cart;
import com.hyjoy.entity.CartItem;
import com.hyjoy.entity.Product;
import com.hyjoy.service.ProductService;
import com.hyjoy.service.impl.ProductServiceImpl;
import com.hyjoy.util.BeanFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Created by hyjoy on 2018/4/5.
 */
public class CartServlet extends BaseServlet {
    /**
     * @param request
     * @param response
     * @return
     */
    public String clear(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 获取购物车，执行清空操作
        getCart(request).clearCart();
        // 重定向
        response.sendRedirect(request.getContextPath() + "/jsp/cart.jsp");
        return null;
    }

    public String remove(HttpServletRequest request, HttpServletResponse response) throws IOException {
        // 获取商品Id
        String pid = request.getParameter("pid");
        // 获取购物车执行移除
        getCart(request).removeFromCart(pid);
        // 重定向
        response.sendRedirect(request.getContextPath() + "/jsp/cart.jsp");
        return null;
    }

    public String add2Cart(HttpServletRequest request, HttpServletResponse response) {
        try {
            // 获取pid count

            String pid = request.getParameter("pid");
            int count = Integer.parseInt(request.getParameter("count"));
            // 封装cartitem
            // 调用service获取product
            ProductService productService = new ProductServiceImpl();
            Product product = productService.getById(pid);

            // 创建cartItem
            CartItem item = new CartItem(product, count);
            // 将cartitem加入购物车
            Cart cart = getCart(request);
            cart.add2cart(item);
            // 重定向
//            request.setAttribute("cart", cart);
            response.sendRedirect(request.getContextPath() + "/jsp/cart.jsp");
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("msg", "加入购物车失败");
            return "/jsp/msg.jsp";
        }
        return null;
    }


    /**
     * 获取购物车
     *
     * @param request
     * @return
     */
    private Cart getCart(HttpServletRequest request) {
        Cart cart = (Cart) request.getSession().getAttribute("cart");
        if (cart == null) {
            cart = new Cart();
            // 将cart放入session中
            request.getSession().setAttribute("cart", cart);
        }
        return cart;
    }
}
